// This is not safe and if the print fails it will crash because i'm not 
// setting up the jmpbuf (see libpng.org/pub/png/libpng-1.0.3-manual.html)

#include <png.h>
#include <stdio.h>
#include <stdlib.h>

int print_png(char *data, int height, int width, char* fileName) {
  FILE * fp;
  png_structp png_ptr;
  png_infop info_ptr;
  int i,j,k,l=0;
  png_bytep *row_pointers;
  png_color palette[256];

  for(i=0;i<8;i++){
    for(j=0;j<8;j++){
      for(k=0;k<4;k++){
	palette[l].red=i*32+31;
	palette[l].green=j*32+31;
	palette[l++].blue=k*64+63;
      }
    }
  }

  row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);

  for(i=0;i<height;i++){
    row_pointers[i]=data+i*width;
  }

  fp = fopen(fileName, "wb");
  if(fp==NULL){
    printf("Error opening output image\n");
    return 1;
  }

  png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL,
				    NULL, NULL);
  if(png_ptr==NULL){
    printf("Error creating png_ptr\n");
    return 1;
  }

  info_ptr = png_create_info_struct(png_ptr);
  if(info_ptr==NULL){
    png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
    printf("Error creating info_ptr\n");
    return 1;
  }
  
  png_init_io(png_ptr, fp);

  png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_PALETTE,
	       PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,
	       PNG_FILTER_TYPE_DEFAULT);

  png_set_PLTE(png_ptr, info_ptr, palette, 256);
  
  png_write_info(png_ptr, info_ptr);

  png_write_image(png_ptr, row_pointers);

}

